/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.company.management.controller;

import java.io.Serializable;

import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.company.management.entity.Employee;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.company.management.entity.EmployeeGroup;
import org.company.management.controller.exceptions.NonexistentEntityException;

/**
 *
 * @author Paner
 */
@SuppressWarnings("serial")
public class EmployeeGroupJpaController implements Serializable {

    public EmployeeGroupJpaController() {
    	emf = Persistence.createEntityManagerFactory("Management");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(EmployeeGroup employeeGroup) {
        if (employeeGroup.getEmployeeList() == null) {
            employeeGroup.setEmployeeList(new ArrayList<Employee>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Employee> attachedEmployeeList = new ArrayList<Employee>();
            for (Employee employeeListEmployeeToAttach : employeeGroup.getEmployeeList()) {
                employeeListEmployeeToAttach = em.getReference(employeeListEmployeeToAttach.getClass(), employeeListEmployeeToAttach.getId());
                attachedEmployeeList.add(employeeListEmployeeToAttach);
            }
            employeeGroup.setEmployeeList(attachedEmployeeList);
            em.persist(employeeGroup);
            for (Employee employeeListEmployee : employeeGroup.getEmployeeList()) {
                EmployeeGroup oldGroupidOfEmployeeListEmployee = employeeListEmployee.getGroupid();
                employeeListEmployee.setGroupid(employeeGroup);
                employeeListEmployee = em.merge(employeeListEmployee);
                if (oldGroupidOfEmployeeListEmployee != null) {
                    oldGroupidOfEmployeeListEmployee.getEmployeeList().remove(employeeListEmployee);
                    oldGroupidOfEmployeeListEmployee = em.merge(oldGroupidOfEmployeeListEmployee);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(EmployeeGroup employeeGroup) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            EmployeeGroup persistentEmployeeGroup = em.find(EmployeeGroup.class, employeeGroup.getId());
            List<Employee> employeeListOld = persistentEmployeeGroup.getEmployeeList();
            List<Employee> employeeListNew = employeeGroup.getEmployeeList();
            List<Employee> attachedEmployeeListNew = new ArrayList<Employee>();
            for (Employee employeeListNewEmployeeToAttach : employeeListNew) {
                employeeListNewEmployeeToAttach = em.getReference(employeeListNewEmployeeToAttach.getClass(), employeeListNewEmployeeToAttach.getId());
                attachedEmployeeListNew.add(employeeListNewEmployeeToAttach);
            }
            employeeListNew = attachedEmployeeListNew;
            employeeGroup.setEmployeeList(employeeListNew);
            employeeGroup = em.merge(employeeGroup);
            for (Employee employeeListOldEmployee : employeeListOld) {
                if (!employeeListNew.contains(employeeListOldEmployee)) {
                    employeeListOldEmployee.setGroupid(null);
                    employeeListOldEmployee = em.merge(employeeListOldEmployee);
                }
            }
            for (Employee employeeListNewEmployee : employeeListNew) {
                if (!employeeListOld.contains(employeeListNewEmployee)) {
                    EmployeeGroup oldGroupidOfEmployeeListNewEmployee = employeeListNewEmployee.getGroupid();
                    employeeListNewEmployee.setGroupid(employeeGroup);
                    employeeListNewEmployee = em.merge(employeeListNewEmployee);
                    if (oldGroupidOfEmployeeListNewEmployee != null && !oldGroupidOfEmployeeListNewEmployee.equals(employeeGroup)) {
                        oldGroupidOfEmployeeListNewEmployee.getEmployeeList().remove(employeeListNewEmployee);
                        oldGroupidOfEmployeeListNewEmployee = em.merge(oldGroupidOfEmployeeListNewEmployee);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = employeeGroup.getId();
                if (findEmployeeGroup(id) == null) {
                    throw new NonexistentEntityException("The employeeGroup with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            EmployeeGroup employeeGroup;
            try {
                employeeGroup = em.getReference(EmployeeGroup.class, id);
                employeeGroup.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The employeeGroup with id " + id + " no longer exists.", enfe);
            }
            List<Employee> employeeList = employeeGroup.getEmployeeList();
            for (Employee employeeListEmployee : employeeList) {
                employeeListEmployee.setGroupid(null);
                employeeListEmployee = em.merge(employeeListEmployee);
            }
            em.remove(employeeGroup);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<EmployeeGroup> findEmployeeGroupEntities() {
        return findEmployeeGroupEntities(true, -1, -1);
    }

    public List<EmployeeGroup> findEmployeeGroupEntities(int maxResults, int firstResult) {
        return findEmployeeGroupEntities(false, maxResults, firstResult);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	private List<EmployeeGroup> findEmployeeGroupEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(EmployeeGroup.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public EmployeeGroup findEmployeeGroup(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(EmployeeGroup.class, id);
        } finally {
            em.close();
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public int getEmployeeGroupCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<EmployeeGroup> rt = cq.from(EmployeeGroup.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
